import React, { useState, useEffect } from 'react';
import { Card, Button, Row, Col, Typography, Modal, InputNumber, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useUserStore } from '../store/user';
import { getProductList, getRecommendProducts } from '../api/product';
import { createOrder } from '../api/order';
import { ShoppingCartOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title, Paragraph } = Typography;

const HomeUser: React.FC = () => {
  const navigate = useNavigate();
  const isLogin = !!localStorage.getItem('token');
  const user = isLogin ? JSON.parse(localStorage.getItem('user') || '{}') : null;
  const [productList, setProductList] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);
  const [buyModal, setBuyModal] = useState(false);
  const [buyProduct, setBuyProduct] = useState<any>(null);
  const [buyQuantity, setBuyQuantity] = useState(1);
  const [confirmModal, setConfirmModal] = useState(false);
  const [recommendedProducts, setRecommendedProducts] = useState<any[]>([]);

  const setUserInfo = useUserStore((state) => state.setUserInfo);

  useEffect(() => {
    getProductList(page, pageSize).then(res => {
      const records = res.data?.data?.records || [];
      setProductList(records);
    });
  }, [page, pageSize]);

  // handleBuy 只弹出弹框和设置商品信息
  const handleBuy = (product: any) => {
    setBuyProduct(product);
    setBuyQuantity(1);
    setBuyModal(true);
  };

  // handleConfirmBuy 负责下单、推荐接口和关闭弹框
  const handleConfirmBuy = async () => {
    if (!buyProduct) return;
    const orderParam = {
      productId: buyProduct.id,
      quantity: buyQuantity
    };
    try {
      await createOrder(orderParam);
      message.success('下单成功');
      // 下单后直接用商品列表接口获取推荐
      const res = await getProductList(page, pageSize, buyProduct.id);
      const records = res.data?.data?.records || [];
      setProductList(records);
      setBuyModal(false);
    } catch (error) {
      message.error('下单失败');
    }
  };

  const handleCancelBuy = () => {
    setBuyModal(false);
    getProductList(page, pageSize).then(res => {
      const records = res.data?.data?.records || [];
      setProductList(records);
    });
  };

  return (
    <div style={{ padding: 24 }}>
      {/* 顶部栏 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={2} style={{ margin: 0 }}>皮蛋商场1</Title>
        {/* 已登录状态下只显示用户信息和个人中心按钮，不显示登录/注册按钮 */}
        {isLogin && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <img src={user?.avatar} alt="avatar" style={{ width: 32, height: 32, borderRadius: '50%' }} />
            <span>{user?.nickname || user?.username}</span>
            <Button type="link" onClick={() => navigate('/profile')}>个人中心</Button>
          </div>
        )}
      </div>
      {recommendedProducts.length > 0 && (
        <h2 style={{margin: '24px 0'}}>为你推荐</h2>
      )}
      <Row gutter={[16, 16]} justify="center">
        {productList.map(product => (
          <Col key={product.id} xs={24} sm={12} md={8} lg={6}>
            <Card
              hoverable
              cover={
                <img
                  alt={product.productName}
                  src={product.productImg || 'https://via.placeholder.com/400x180?text=暂无图片'}
                  style={{ height: 180, objectFit: 'cover' }}
                />
              }
              actions={[
                <Button
                  type="primary"
                  key="buy"
                  htmlType="button"
                  onClick={() => handleBuy(product)}
                  disabled={product.enableFlag === false}
                  style={{
                    background: 'linear-gradient(135deg, #1890ff, #52c41a)',
                    border: 'none',
                    borderRadius: '20px',
                    boxShadow: '0 4px 8px rgba(0, 0, 0, 0.2)',
                    transition: 'all 0.3s ease',
                  }}
                  icon={<ShoppingCartOutlined />}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.transform = 'scale(1.05)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = 'scale(1)';
                  }}
                >
                  购买
                </Button>
              ]}
            >
              <Card.Meta
                title={<span>{product.productName || product.name} <span style={{ color: '#faad14', fontWeight: 'bold' }}>￥{product.price}</span></span>}
                description={<>
                  <Paragraph ellipsis={{ rows: 2 }}>{product.desc || product.productDesc}</Paragraph>
                  <div>库存：{product.stock}</div>
                </>}
              />
            </Card>
          </Col>
        ))}
      </Row>
      <Modal
        title={`购买${buyProduct?.productName || buyProduct?.name || ''}`}
        open={buyModal}
        onOk={handleConfirmBuy}
        onCancel={handleCancelBuy}
        okText="确认购买"
        cancelText="取消"
        destroyOnClose
      >
        <div style={{ marginBottom: 12 }}>请输入购买数量：</div>
        <InputNumber min={1} max={buyProduct?.stock} value={buyQuantity} onChange={v => setBuyQuantity(Number(v))} />
      </Modal>
      <Modal
        title="购买成功"
        open={confirmModal}
        onOk={() => setConfirmModal(false)}
        onCancel={() => setConfirmModal(false)}
        okText="确定"
        cancelText="取消"
        centered
        width={300}
      >
        <p>您的订单已成功创建！</p>
        <p>感谢您的购买，祝您购物愉快！</p>
      </Modal>
    </div>
  );
};

export default HomeUser; 